// index.ts
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { Message } from '@/plugins/element'
import NProgress from 'nprogress'
import { dealResponse, dealResponseError } from '@/plugins/dealResponse'
import { response } from '@/ts/type'
import { useToken } from '@/store'

const baseURL = '/api/'
const timeout = 4000

// 导出Request类，可以用来自定义传递配置来创建实例
export class Request {
  // axios 实例
  instance: AxiosInstance
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = { baseURL, timeout, withCredentials: true }

  constructor(config: AxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config))
    this.instance.interceptors.request.use(
      // @ts-ignore
      (config: AxiosRequestConfig) => {
        NProgress.start()
        const Token = useToken()
        // 一般会请求拦截里面加token，用于后端的验证
        config.headers = { Authorization: Token.token }
        return config
      },
      (err: any) => {
        // 请求错误，这里可以用全局提示框进行提示
        Message.error(err)
        return Promise.reject(err)
      }
    )

    this.instance.interceptors.response.use(
      (res: AxiosResponse<response<any>>) => dealResponse(res)
      ,
      (err: any) => dealResponseError(err)
    )
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config)
  }

  public get<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.get(url, config)
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.post(url, data, config)
  }

  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.put(url, data, config)
  }

  public delete<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.delete(url, config)
  }
}

// 默认导出Request实例
export default new Request({})